<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="formData" ref="formRef" vloading="formLoading" label-width="auto">
      <el-row v-if="sendType == 'delay'">
        <el-col :offset="6" :span="24">
          <el-form-item label="延迟时间" prop="ownerId">
            <el-select v-model="formData.delayTime" placeholder="请选择延迟时间">
              <el-option label="10分钟" value="10" />
              <el-option label="30分钟" value="30" />
              <el-option label="60分钟" value="60" />
              <el-option label="120分钟" value="120" />
              <el-option label="240分钟" value="240" />
              <el-option label="360分钟" value="360" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :offset="6" :span="24">
          <el-form-item label="发送时间" prop="sendTime">
            <el-date-picker
              v-model="formData.sendTime"
              placeholder="请输入发送时间"
              :clearable="true"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="MailDelayTimeSelect" lang="ts">
import { formatDate } from '@/utils/formatTime'
import dayjs from 'dayjs'
const message = useMessage() // 消息弹窗
const formLoading = ref(false)
const dialogTitle = ref('定时发送')
const dialogVisible = ref(false)
const formRef = ref()

const formData = ref({
  sendTime: undefined,
  delayTime: undefined
})
const sendType = ref()

/** 打开弹窗 */
const open = async (type) => {
  sendType.value = type
  if (type == 'delay') dialogTitle.value = '延时发送'
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  if (sendType.value == 'delay' && formData.value.delayTime == undefined) {
    message.error('请选择延迟时间')
    return
  }
  if (sendType.value == 'scheduled' && formData.value.sendTime == undefined) {
    message.error('请选择发送时间')
    return
  }
  let time = undefined as any
  const now = new Date()
  if (sendType.value == 'delay') {
    time = formatDate(new Date(now.getTime() + formData.value.delayTime! * 60 * 1000))
  } else {
    const sendTime = dayjs(formData.value.sendTime)
    if (sendTime.isBefore(now)) {
      message.error('发送时间不能小于当前时间')
      return
    }
    if (formData.value.sendTime) time = formData.value.sendTime
  }
  dialogVisible.value = false
  emit('success', time, sendType.value)
}
</script>
